<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车列表</title>
    <script src="./js/jquery-1.11.1.min.js"></script>
    <script src="./js/layer/layer.js"></script>
    <link rel="stylesheet" href="./css/header.css">
    <link rel="stylesheet" href="./css/shopCar.css">
    <link rel="stylesheet" href="./css/footer.css">
</head>
<body style="background-color: #fff;">
    
    <div id="topHeader"></div>
    <div id="Header" style="position: relative;">
        <div class="margin">
            <table width="100%" cellpadding="0" cellspacing="0" border="0" class="table">
                <tbody>
                    <tr>
                    <td width="240" height="118">
                        <a href="./index.html"><img class="header_logo" src="./img/logo.png"></a>
                    </td>

                    <td width="281" style="padding-top:20px"></td>
                        <td align="center">
                            <table width="100%" border="0" cellpadding="0" cellspacing="0">
                                <tbody>
                                    <tr>
                                        <td height="50" background="./img/checkout_bg.gif">
                                            <table width="210" border="0" cellpadding="0" cellspacing="0">
                                                <tbody>
                                                    <tr>
                                                        <td width="50" align="center" valign="bottom" bgcolor="#FA6CA1"><img src="./img/1_w.gif" width="17" height="45"></td>
                                                        <td valign="middle" bgcolor="#FA6CA1" class="check_on">购物篮</td>
                                                        <td width="24" align="right"><img src="./img/arrow_pink.jpg" width="24" height="50"></td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </td>
                                        <td background="./img/checkout_bg.gif">
                                            <table width="220" border="0" cellpadding="0" cellspacing="0">
                                                <tbody>
                                                    <tr>
                                                        <td width="50" align="center" valign="bottom"><img src="./img/2_p.gif" width="31" height="46"></td>
                                                        <td valign="middle" class="check_of">填写订单资料</td>
                                                        <td width="24" align="right"><img src="./img/arrow_white.gif" width="24" height="50"></td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </td>
                                        <td background="./img/checkout_bg.gif">
                                            <table width="220" border="0" cellpadding="0" cellspacing="0">
                                                <tbody>
                                                    <tr>
                                                        <td align="center" valign="bottom"><img src="./img/3_p.gif" width="31" height="46"></td>
                                                        <td class="check_of">确认订单</td>
                                                        <td width="24" align="right" bgcolor="#FFFFFF"><img src="./img/arrow_white.gif" width="24" height="50"></td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </td>
                                    </tr>
                                </tbody>
                            </table> 
                         </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <!-- 购物车列表 -->
    <div class="carContent">
        <!-- 全部商品 -->
        <div class="cart-filter-bar">
            <ul class="switch-cart">
                <li class="switch-cart-item curr">
                    <a href="//cart.jd.com/cart.action">
                        <em>全部商品</em>
                        <span class="number">0</span>
                    </a>
                </li>
            </ul>
            
            <div class="clr"></div>
            <div class="w-line">
                <div class="floater" style="width: 78px; left: 0px;"></div>
            </div>
        </div>
        <!-- 全选 列标题 -->
        <div class="cart-thead">
            <div class="column t-checkbox">
                <div class="cart-checkbox">
                    <input type="checkbox" id="toggle-checkboxes_up" name="toggle-checkboxes" class="allcheckbox" checked="checked">
                </div>全选
            </div>
            <div class="column t-goods">商品</div>
            <div class="column t-props"></div>
            <div class="column t-price">单价</div>
            <div class="column t-quantity">数量</div>
            <div class="column t-sum">小计</div>
            <div class="column t-action">操作</div>
        </div>
        <!-- 列表 -->
        <div class="cart-item-list">
            <div class="cart-tbody">
                <!-- <div class="item-list">   商品列表
                    <div class="item-single  item-item  item-selected ">  一个商品
                        <div class="cell p-checkbox">
                            <div class="cart-checkbox">
                                <input type="checkbox" name="checkItem" checked="checked">
                            </div>
                        </div>
                        <div class="cell p-goods">
                            <div class="goods-item">
                                <div class="p-img">
                                    <a href="#" class="J_zyyhq_44362704032">
                                        <img  src="./img/shoppinglist1-1.jpg">
                                    </a>
                                </div>
                                <div class="item-msg">
                                    <div class="p-name">
                                        <a  href="#" >悦木之源 菌菇水 </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="cell p-price p-price-new">
                            <p class="plus-switch">
                                <strong>HK$<span>153.0</span></strong>
                            </p>                                                   
                        </div>
                        <div class="cell p-quantity">
                            <div class="quantity-form">
                                <a href="javascript:void(0);" class="decrement decrease_num">-</a>
                                <input autocomplete="off" type="text" class="itxt quantity" value="1" step="1" minnum="1">
                                <a href="javascript:void(0);" class="increment increase_num">+</a>
                            </div>                                                  
                        </div>
                        <div class="cell p-sum">
                            <strong>HK$<span>153.0</span></strong>                                                           
                        </div>

                        <div class="cell p-ops">
                            <a data-name="" data-more="" class="cart-remove" href="javascript:void(0);" ob="false">删除</a>
                        </div>
                    </div>
                   
                </div> -->
            </div>

        </div>
        <!-- 购物车底部 结算栏 -->
        <div class="options-box">
            <div class="select-all">
                <div class="cart-checkbox">
                    <input type="checkbox" id="toggle-checkboxes_down" name="toggle-checkboxes" class="allcheckbox" checked="checked">
                </div>全选
            </div>
            <div class="operation">
                <a href="#"  class="remove-batch">删除选中商品</a>
                <a href="#" class="cleaner-opt J_clr_all" title="亲，点我可快速清理购物车商品哦！">清理购物车</a>
            </div>
            <div class="clr"></div>
            <div class="toolbar-right">
                <div class="normal">
                    <div class="comm-right">
                        <div class="btn-area">
                            <a href="#" class="submit-btn">去结算<b></b></a>
                        </div>
                        <div class="price-sum">
                            <div>
                                <span class="txt txt-new">总价：</span>
                                <span class="price sumPrice">
                                    <em data-bind="153.0">HK$<span>153.00</span></em>
                                </span>
                                <br>
                            </div>
                        </div>
                        <div class="amount-sum">
                            已选择<em>1</em>件商品
                        </div>
                        <div class="clr"></div>
                    </div>
                </div>
                
            </div>
            
        </div>
    </div>
    <p class="cart-null">
        购物车里空空如也~快去选购吧
    </p>




    <footer>
        <div class="footer_info_wrapper">
            <div class="footer_info">
                <span class="footer_info_img">
                    <img src="./img/footer_info_secu.png" alt="">
                    <a href="#">
                        <img src="./img/footer_info_secu3.png" style="height:47px;">
                    </a>
                </span><br>
                价格以美元与港币为结账交易货币，其他货币价格只供参考。
                <a href="#" style="color:#EB6495">* 详情请按此</a><br>
                *折扣 % - 基于建议价与现价折后优惠% 
            </div>
        </div>

        <div class="footer_cpy_wrapper">
            <div class="footer_cpy">
                <p>Copyright 2000-2020 Sa Sa dot Com Limited 版权所有. </p>
                <p>
                    <a href="#" style="color:#eee;">莎莎国际</a>
                    控股有限公司成员
                </p>
            </div>
        </div>
    </footer>
   
    <script>
        $(function(){
            $("#topHeader").load("./page/topHeader.html");
            
           
        })
        $(function(){
            showSmallCart()
            function sendAjax(url,obj,fn){
                $.ajax({
                    url: url,
                    type: "post",
                    headers: {
                        token: localStorage.getItem("token")
                    },
                    data: obj,
                }).then(function(res){
                    fn(res);
                })
            }
            function showSmallCart(){
                    sendAjax("./api/getCart",{uid: JSON.parse(localStorage.getItem("users")).uId},function(res){
                        if (!res.data) {
                            $("#cart-box").find(".content_null").css("display","block").siblings(".content_catalog").css("display","none")
                            $("#cart-box").find(".shop-cart").children("em").text("0");
                            return;
                        }else{
                            // console.log(res.data);
                            let cartList=res.data;
                            // console.log(cartList)
                            let smallCartsSumpirce=0;
                            let smallCartsSumlength=0;
                            $("#cart-box").find(".shop-cart").children("em").text(cartList.length);
                            $("#cart-box").find(".content_null").css("display","none").siblings(".content_catalog").css("display","block")
                            var cartStr=`<ul id="shoppingCartDetails"><!-- 每一个li 是一个购物车内的商品 -->`;
                            cartList.forEach((item,index)=>{
                                cartStr+=`<li class="border-dashed"><!-- left 是一个图片 --><span class="box_left"><a href="./detail.html?gid=${item.gid}">`;
                                cartStr+=`<img src="${item.giconimgsrc}" ></a></span><!-- right 有品牌 标题 价格 数量 --><span class="box_right">`;
                                cartStr+=`<h1><a href="javascript:;">${item.gbrand}</a><br><a href="javascript:;">${item.gtitle}</a></h1><b class="fon-price">`;
                                cartStr+=`HK$<span>${item.gnowpirce}</span><em> x ${item.num}</em></b><a class="btn-delete" data-info='${JSON.stringify(item)}'>X</a></span></li></ul>`;
                                smallCartsSumpirce+=item.gnowpirce*item.num;
                                smallCartsSumlength+=item.num;
                            });
                            cartStr+=`</ul>`;
                            $(".rank-list").html(cartStr);

                            let cartMsgStr=`<div class="fon-price" align="left" style="width:40%">&nbsp;<span class="fon-MSYH">共</span>`;
                                cartMsgStr+=`&nbsp;<b><span id="basketitem">${smallCartsSumlength}</span></b>&nbsp;<span class="fon-MSYH">件商品</span></div>`;
                                cartMsgStr+=`<div class="fon-price" align="right" style="width:60%"><span class="fon-MSYH">共计：</span>`;
                                cartMsgStr+=`<b>HK$<span id="baskettotal">${smallCartsSumpirce}</span></b></div><a href="./shoppingCar.html">`;
                                cartMsgStr+=`<div class="btn_checkout">查看购物车</div></a>`;      
                            $(".content_notice").html(cartMsgStr);
                            $(".rank-list").on("click",".btn-delete",function(){
                                var self = this;
                                var cid = $(this).data("info").cid;
                                var delNum= $(this).data("info").num;
                                var delPirce= ($(this).data("info").gnowpirce)*delNum;
                                console.log(cid,delNum,delPirce)
                                layer.confirm('是否将该商品从购物车中删除?', {btn: ['确认','取消'] }, 
                                    function(){
                                        sendAjax("./api/delete",{cid},function(res){
                                            layer.msg("删除成功");
                                            $(self).parents(".border-dashed").remove();
                                            setTimeout(function(){
                                                console.log(res);
                                                $("#basketitem").text($("#basketitem").text()-delNum);
                                                $("#baskettotal").text($("#baskettotal").text()-delPirce);
                                                var cartxtNum=$("#cart-box").find(".shop-cart").children("em").text();
                                                if(cartxtNum!=0){
                                                    $("#cart-box").find(".shop-cart").children("em").text(cartxtNum-1);
                                                    if(cartxtNum==1){
                                                        $("#cart-box").find(".shop-cart").children("em").text(0)
                                                        $("#cart-box").find(".content_null").css("display","block").siblings(".content_catalog").css("display","none");
                                                    }
                                                }
                                            },100);
                                        })
                                    }, function(){return;}
                                );
                            });
                        }
                    })
                }




        })
        
                    

        $(function () {
            testLogin();
            
            function sendAjax(url,obj,fn){
                $.ajax({
                    url: url,
                    type: "post",
                    headers: {
                        token: localStorage.getItem("token")
                    },
                    data: obj,
                }).then(function(res){
                    fn(res);
                })
            }
            function testLogin(){
                if(!localStorage.getItem("users")){
                    layer.confirm('您还没有登录,请先登录或注册', {btn: ['登录','注册']}, function(){
                        layer.msg("即将跳转到登录页面");
                        setTimeout(function(){
                            javascrtpt:window.location.href='http://localhost:8585/login.html'
                        },1000)
                    }, function(){
                        layer.msg("即将跳转到注册页面");
                        setTimeout(function(){
                            javascrtpt:window.location.href='http://localhost:8585/register.html'
                        },1000)
                    });
                    $(".carContent").css("display","none").siblings(".cart-null").css("display","block")
                }
            }
            function addScript(url){
                var script = document.createElement('script');
                script.setAttribute('type','text/JavaScript');
                script.setAttribute('src',url);
                document.getElementsByTagName('head')[0].appendChild(script);
            }

            
            sendAjax("./api/getCart",{uid: JSON.parse(localStorage.getItem("users")).uId},function(res){
                if (!res.data) {
                    return;
                }
                console.log(res);
                
                var strHtml = `<div class="item-list">`;
                [...res.data].forEach(function (el) {
                    strHtml += `<!-- 一个商品 --><div class="item-single  item-item  item-selected "><div class="cell p-checkbox">`;
                    strHtml += `<div class="cart-checkbox"><input type="checkbox" name="checkItem" checked="checked"></div>`;
                    strHtml += `</div><div class="cell p-goods"><div class="goods-item"><div class="p-img"><a href="#">`;
                    strHtml += `<img  src="${el.giconimgsrc}"></a></div><div class="item-msg"><div class="p-name">`;
                    strHtml += `<a  href="#" >${el.gbrand} ${el.gtitle} </a></div></div></div></div><div class="cell p-price p-price-new">`;
                    strHtml += `<p class="plus-switch"><strong>HK$<span>${el.gnowpirce}</span></strong></p></div><div class="cell p-quantity">`;
                    strHtml += `<div class="quantity-form"><a href="javascript:void(0);" class="decrement decrease_num" data-cid="${el.cid}">-</a>`;
                    strHtml += `<input autocomplete="off" type="text" class="itxt quantity" value=${el.num} step="1" minnum="1">`;
                    strHtml += `<a href="javascript:void(0);" class="increment increase_num" data-cid="${el.cid}">+</a></div></div>`;
                    strHtml += `<div class="cell p-sum"><strong>HK$<span>${(el.gnowpirce*el.num).toFixed(2)}</span></strong></div><div class="cell p-ops">`;
                    strHtml += `<a data-cid="${el.cid}" class="cart-remove" href="javascript:void(0);" ob="false">删除</a></div></div>`;
                });
                strHtml += `</div>`;
                $(".cart-tbody").html(strHtml);
                var cks,allCks=[];
                showCartNull();
                init();
                function init(){
                    cks=document.querySelectorAll("[type=checkbox]");
                    cks=Array.from(cks); 
                    $(cks).on("click",ckeckClickHandler);
                    allCks.push(cks.shift(),cks.pop());
                    $(".remove-batch").on("click",delClick);
                    $(".cleaner-opt").on("click",delClick);
                    $(".cart-remove").on("click",delClick);
                    cartListNumber();
                    showCartNull();
                    totleSum();
                }



                 // 删除商品函数
                // function deletItem(elem){
                //     console.log(elem);
                //     $(elem).remove();
                //     totleSum();
                //     cartListNumber();
                // }
                // 删除选中商品
                function delClick(){
                    // $(".remove-batch").on("click",delClick); 删除选中
                    // $(".cleaner-opt").on("click",delClick); 全删
                    // $(".cart-remove").on("click",delClick); 单个删
                    var cidList;
                    var $delarr;
                    if($(this).hasClass("remove-batch")){
                        $delarr=$(this).parents(".carContent").find(".item-selected");
                        cidList=[];
                        for (let j=0;j<$delarr.length;j++){
                            cidList.push($delarr.eq(j).find(".p-ops").children("a").data("cid"));
                        }
                        
                    }
                    if($(this).hasClass("cleaner-opt")){
                        $delarr=$(this).parents(".carContent").find(".item-item");
                        cidList=[];
                        for (let j=0;j<$delarr.length;j++){
                            cidList.push($delarr.eq(j).find(".p-ops").children("a").data("cid"));
                        }
                       
                    }
                    if($(this).hasClass("cart-remove")){
                        $delarr=$(this).parents(".item-item");
                        cidList=[];
                        for (let j=0;j<$delarr.length;j++){
                            cidList.push($delarr.eq(j).find(".p-ops").children("a").data("cid"));
                        }
                    }
                    console.log(cidList,$delarr)
                    confirmDelete(cidList,$delarr);
                    
                   
                }

                // 询问是否删除
                function confirmDelete(arr,parList){
                    layer.confirm('真的要删除吗', {btn: ['确认','取消']}, 
                        function(){
                            for(let i=0;i<arr.length;i++){
                                sendAjax("./api/delete",{cid:arr[i]},function(res){
                                    parList[i].remove();
                                });
                            }
                            layer.msg("删除成功");
                            setTimeout(function(){
                                totleSum();
                                cartListNumber();
                                showCartNull();
                            },100)
                            
                        },
                        function(){
                            return;
                        }
                    );
                    
                }
               

                // 全选框
                function ckeckClickHandler(){
                    if(allCks.some((item)=>{
                        return this==item;
                    })){
                        cks.forEach((item)=>{
                            item.checked=this.checked; 
                            removeSlected(item,this.checked)
                        });
                        allCks.forEach((item)=>{
                            item.checked=this.checked; 
                        })
                        
                    }else{
                        var bool=cks.every(function(item){
                            return item.checked;
                        })
                        $(allCks).prop("checked",bool);
                        removeSlected(bool==true?cks:this,this.checked)
                    }
                
                }
                // 全选框的函数 removeSlected
                function removeSlected(elem,reBool){
                    if(reBool){
                        $(elem).parents(".item-item").addClass("item-selected");
                    }
                    else{
                        $(elem).parents(".item-item").removeClass("item-selected");
                    }
                    totleSum();
                    cartListNumber();
                }

                //计算价格函数 总价
                function totleSum(){
                    var sum=0;
                    for(let i=0;i<$(".item-selected").length;i++){
                        sum+=(parseFloat($(".item-selected").eq(i).find(".p-sum").find("span").text()));     
                    }
                    if(!sum) sum=new Number(00);
                    $(".sumPrice").find("span").text(sum.toFixed(2));
                }

                //计算价格函数 共选中几件商品
                function cartListNumber(){
                    $(".switch-cart-item").find(".number").text($(".item-list").children().length);
                    $(".amount-sum").find("em").text($(".item-selected").length);
                }

                // 购物车列表如果是空的 则显示另一个div
                function showCartNull(){
                    if($(".item-list").children().length==0){
                        $(".carContent").css("display","none").next(".cart-null").css("display","block");
                    }else{
                        $(".carContent").css("display","block").next(".cart-null").css("display","none");
                    }
                }




                //减法
                $(".cart-tbody").on("click", ".decrease_num", function () {
                    var num = $(this).next('.quantity').val();
                    if (num <= 1) {
                        return;
                    }
                    num--;
                    $(this).next('.quantity').val(num);

                    var price = $(this).parents(".p-quantity").siblings(".p-price").find("span").text();
                    $(this).parents(".p-quantity").siblings(".p-sum").find("span").text((price*num).toFixed(2));

                    var cid = $(this).data("cid");
                    console.log("cid"+cid);
                    sendAjax("./api/changeCartNuM",{cid,num},function(res){
                        setTimeout(function(){
                            totleSum();
                            cartListNumber();
                        },100)
                    });

                });
                //加法
                $(".cart-tbody").on("click", ".increase_num", function () {
                    var num = $(this).prev('.quantity').val();
                    num++;
                    $(this).prev('.quantity').val(num);

                    var price = $(this).parents(".p-quantity").siblings(".p-price").find("span").text();
                    $(this).parents(".p-quantity").siblings(".p-sum").find("span").text((price*num).toFixed(2))

                    var cid = $(this).data("cid");
                    console.log("cid"+cid);
                    sendAjax("./api/changeCartNuM",{cid,num},function(res){
                        setTimeout(function(){
                            totleSum();
                            cartListNumber();
                        },100)
                    });
                })



           


            });


        })
   
    </script>
</body>
</html>